package hu.ikti.oamadmin.ws.gwsync;

import java.util.List;

import hu.ikti.oamadmin.beans.BaseBean;
import hu.ikti.oamadmin.types.entities.Bundle;
import hu.ikti.oamadmin.types.entities.Service;
import hu.ikti.oamadmin.types.entities.ServiceProfile;
import hu.ikti.oamadmin.ws.gwsync.impl.MappedBundle;
import hu.ikti.oamadmin.ws.gwsync.impl.SyncRequest;
import hu.ikti.oamadmin.ws.gwsync.impl.SyncResponse;

import javax.ejb.Stateless;
import javax.jws.WebMethod;
import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;

import org.jboss.seam.annotations.Name;

@Name("gwsyncService")
@Stateless
@WebService(name = "GwSyncService", serviceName = "GwSyncService")
@SOAPBinding(style = SOAPBinding.Style.DOCUMENT, use = SOAPBinding.Use.LITERAL, parameterStyle = SOAPBinding.ParameterStyle.WRAPPED)
public class SyncService extends BaseBean implements SyncServiceRemote{

	@WebMethod
	public SyncResponse synchronise(SyncRequest request) {
		
		ServiceProfile serviceprofile = (ServiceProfile) entityManager.find(
				ServiceProfile.class, request.getID());
		
		List<Bundle> requiredBundles= serviceprofile.getBundles();
		SyncResponse response = new SyncResponse();		
		
		response.serviceprofileResources = serviceprofile.getResources(); 
		
		for (Service service : serviceprofile.getServices()){
				response.serviceResources.addAll(service.getResources());
		}
		
		for (Bundle bundle : requiredBundles) {
			boolean install = true;
			
			for (MappedBundle mappedbundle : request.requestBundles){
				if (bundle.getBundleData().getSymbolicName().equalsIgnoreCase(mappedbundle.getSymbolicName()) & (bundle.getBundleData().getVersion()==mappedbundle.getVersion()))
					install = false;
					continue;
			}
			
			if (install){
				MappedBundle tempBundle = new MappedBundle(bundle.getBundleData().getSymbolicName(), bundle.getBundleData().getVersion(), bundle.getBundleData().getByteCode().getBytes());
				response.responseList.add(tempBundle);
				response.bundleResources.addAll(bundle.getResources());
			}	
		}
		
		return response;
	}

}
